<?php

class taskController extends baseController {
	
	
	/* list all tasks*/
	public function index() {
		
		$limit_tasks_per_page = 5;
		
		$tasks = new Tasks ();
		
		$count_tasks = $tasks->getCountTasks();
		$last_page = ceil($count_tasks/$limit_tasks_per_page);
		
		$curent_page =$this->registry->router->getParam( 'page' );
		 
		if ( $curent_page<1) {
			$curent_page = 1;
		}elseif ($curent_page>$last_page){
			$curent_page = $last_page;
		}
		
		$max_page = ($curent_page-1)*$limit_tasks_per_page;
		$this->registry->template->tasks = $tasks->getTasks ( $max_page, $limit_tasks_per_page );
		
		$this->registry->template->last_page = $last_page;
		$this->registry->template->current_page = $curent_page;
	}
	
	
	public function view() {
		
		$news = new Tasks();
		
		$news_id = $this->registry->router->getParam ( 'id' );
		$this->registry->template->task_item = $news->getTasksId( $news_id );
		$this->registry->template->task_comments = $news->getComments ( $news_id );

		$user_for_comment = new User();
		$this->registry->template->user_for_comment = $user_for_comment;
	}
	
	public function comment() {
		$news = new Tasks();
		
		//only authorized user can add comment
		if (Auth::getInstanse ()) {
			if ($this->registry->router->getPostValue ( 'submit' )) {
				$comment = $this->registry->router->getPostValue ( 'comment' );
				$user_id = Auth::getAuthUserId ();
				$task_id = $this->registry->router->getParam ( 'id' );
				
				$news->commentAdd ( $comment, $user_id, $task_id );
				
				//TODO create in AJAX addition
				$this->registry->router->redirect("task","view",array("id"=>$task_id));				
			}
		}
	
	}
	
	
	public function add(){
		if ($this->registry->router->getPostValue ( 'submit' )){
			$user = Auth::getInstanse ();
			if ($user && ($user['role']=='admin' || $user['role']='acm-man')){
				$task = new Tasks();
				
				$title = $this->registry->router->getPostValue ( 'title' );
				$text = $this->registry->router->getPostValue ( 'text' );
				$time_limit = $this->registry->router->getPostValue ( 'time_limit' );
				$memory_limit = $this->registry->router->getPostValue ( 'memory_limit' );
				$points = $this->registry->router->getPostValue ( 'points' );
				
				//TODO find some better solutoin
				//upload file
				
				$file = crc32(time())."_".$_FILES["file"]["name"];
				move_uploaded_file($_FILES["file"]["tmp_name"],__SITE_PATH."/public/upload/" . $file);
				
				$task->addTask($title, $text, $time_limit, $memory_limit, $points, $file);
				
				$this->registry->template->message = "Задачу успішно добавлено";
			}	 
			
		}
	}

}

?>

